new Vue({
    el: '#app',
    data() {
        return {
            tableData: [],
            form: {
                page: 1,
                limit: 15,
            },
            loading: false,
            success: 0,
            error: 0,
            supplier: [],//供应商
        }
    },
    mixins:[importMixin],
    mounted() {
        this.getData();
    },
    methods: {
        getData() {
            const that = this;
            $.ajax({
                headers: requestHeaders(),
                type: 'POST',
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
                data: {
                    Data: 'business_supplier_info',
                    Condition: "Row_Status='0'"
                },
                success: function (Result) {
                    that.supplier = Result
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
        },
        submitUpload(i = 0) {
            const that = this;
            if (i < this.tableData.length) {
                this.loading = true;
                if (this.tableData[i].isError) {
                    this.tableData[i].isStatus = '2';
                    this.tableData[i].Cause = '异常数据'
                    this.error++;
                    this.submitUpload(i + 1);
                } else { //校验通过
                    let obj = {
                        Supplier_Article_SerialNumber: that.tableData[i].Supplier_SerialNumber + "-" + that.tableData[i].Article_Specifications_SerialNumber,
                        Supplier_SerialNumber: that.tableData[i].Supplier_SerialNumber,
                        Article_SerialNumber: that.tableData[i].Article_SerialNumber,
                        Article_Specifications_SerialNumber: that.tableData[i].Article_Specifications_SerialNumber,
                        Shelf: '0',
                        Shelf_Date: getYMDHMSDate(),
                    }
                    let arr = [];
                    $.ajax({
                        headers: requestHeaders(),
                        type: 'POST',
                        url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
                        data: {
                            Data: 'business_supplier_brand',
                            Condition: "Row_Status='0' and Supplier_SerialNumber='" + that.tableData[i].Supplier_SerialNumber
                                + "'\r\n and Brand_SerialNumber='" + that.tableData[i].Brand_SerialNumber + "'"
                        },
                        success: function (data) {
                            let brand = {};
                            if (data.length == 0) {
                                brand = {
                                    business_supplier_brand: [{
                                        Supplier_Brand_SerialNumber: '',
                                        Supplier_SerialNumber: that.tableData[i].Supplier_SerialNumber,
                                        Brand_SerialNumber: that.tableData[i].Brand_SerialNumber
                                    }]
                                }
                            }
                            that.submitForm({ Data: JSON.stringify({ Add: { business_supplier_article: [obj], ...brand } }) }, (res) => {
                                if (res.Status == 'success') {
                                    that.tableData[i].isStatus = '1';
                                    that.tableData[i].Cause = '',
                                        that.success++;
                                } else {
                                    that.tableData[i].isStatus = '2';
                                    that.tableData[i].Cause = '该供应商已经营该商品'
                                    that.error++;
                                }
                                that.submitUpload(i + 1);
                            })
                        },
                        complete: function (XMLHttpRequest) {
                            requestPretreatment(XMLHttpRequest);
                        },
                        dataType: "json"
                    });
                }
            } else if (i != 0) {
                this.loading = false;
                this.$message.success("批量导入结束")
            } else {
                this.$message({
                    message: '请先导入模板后再上传',
                    type: 'warning'
                })
            }
        },
        submitForm(data, callback) {
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalSave`,
                type: 'POST',
                data,
                success: function (res) {
                    callback(res)
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            })
        },
        handleChange({ raw }) {//导入监听文件
            const that = this;
            var reader = new FileReader();
            reader.readAsBinaryString(raw);
            reader.onload = function (e) {
                var data = e.target.result;
                var wb = XLSX.read(data, {
                    type: 'binary' //以二进制的方式读取
                });
                var sheet = wb.Sheets[wb.SheetNames[0]];//sheet0代表excel表格中的第一页
                var json = XLSX.utils.sheet_to_json(sheet);//利用接口实现转换。
                //1.查询商品信息，并展示到页面上
                let sql1 = "";
                let specifications = [];
                json.forEach((item, index) => {
                    if (!specifications.some(i => i == (item['商品规格内码'] + '').trim())) {
                        specifications.push((item['商品规格内码'] + '').trim());
                        if (index == 0) {
                            sql1 = sql1 + "business_article_specifications.Article_Specifications_SerialNumber='" + (item['商品规格内码'] + '').trim() + "'\r\n"
                        } else {
                            sql1 = sql1 + " or business_article_specifications.Article_Specifications_SerialNumber='" + (item['商品规格内码'] + '').trim() + "'\r\n"
                        }
                    }
                })
                $.ajax({
                    headers: requestHeaders(),
                    type: 'POST',
                    url: `${BASE_URL2}/generalBusiness/generalQueryBySQLSerialNumber`,
                    data: {
                        SQLSerialNumber: 'A_business_article_specifications',
                        Condition: '',
                        ExtensionCondition: window.btoa(unescape(encodeURIComponent(`and (${sql1})`))),
                    },
                    success: function (Result) {
                        let arr = [];
                        json.forEach(item => {
                            if (Result.some(i => i.Article_Specifications_SerialNumber == (item['商品规格内码'] + '').trim())
                                && that.supplier.some(i => i.Supplier_SerialNumber == (item['供应商内码'] + '').trim())) {
                                arr.push({
                                    ...Result.filter(i => i.Article_Specifications_SerialNumber == (item['商品规格内码'] + '').trim())[0],
                                    Supplier_Name: that.supplier.filter(i => i.Supplier_SerialNumber == (item['供应商内码'] + '').trim())[0].Supplier_Name,
                                    Article_Specifications_SerialNumber: (item['商品规格内码'] + '').trim(),
                                    Supplier_SerialNumber: (item['供应商内码'] + '').trim(),
                                    isEdit: false,
                                    isStatus: '0',
                                    Cause: '',
                                })
                            } else {
                                arr.push({
                                    Article_Specifications_SerialNumber: (item['商品规格内码'] + '').trim(),
                                    Supplier_SerialNumber: (item['供应商内码'] + '').trim(),
                                    isError: true,
                                    isStatus: '2',
                                    Cause: '异常数据',
                                })
                            }
                        })
                        that.tableData = arr;
                    },
                    complete: function (XMLHttpRequest) {
                        requestPretreatment(XMLHttpRequest);
                    },
                    dataType: "json"
                });
            }
        },
        handleSizeChange(val) {
            this.form.page = 1;
            this.form.limit = val;
        },
        handleCurrentChange(val) {
            this.form.page = val;
        },
        handleEdit(row) {//修改当前行
            row.isEdit = !row.isEdit
        },
        handleRemove(index) {//移除当前行
            this.$confirm('是否要删除此行?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                this.tableData = this.tableData.filter((i, id) => id != (this.form.page - 1) * this.form.limit + index)
            }).catch(() => { });
        },
        handleClean() {//清空
            this.$confirm('是否要清空导入数据?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                this.tableData = []
            }).catch(() => { });
        },
    },
})